package site.marqstree.kotlinmall.ui.activity

import android.Manifest
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.launcher.ARouter
import com.ashokvarma.bottomnavigation.BottomNavigationBar
import kotlinx.android.synthetic.main.activity_main.*
import site.marqstree.kotlin.library.base.extent.begPermissions
import site.marqstree.kotlin.library.base.ui.activity.BaseActivity
import site.marqstree.kotlin.library.base.util.rxbus.RxBus
import site.marqstree.kotlin.library.good.ui.activity.detail.sku.event.EventAddCart
import site.marqstree.kotlin.library.good.ui.fragment.cartlist.event.EventCartSumCountChange
import site.marqstree.kotlin.library.good.ui.fragment.category.CategoryFragment
import site.marqstree.kotlin.library.provider.router.ProviderRouter
import site.marqstree.kotlinmall.R
import site.marqstree.kotlinmall.ui.fragment.home.HomeFragment
import site.marqstree.kotlin.usercenter.ui.fragment.me.MeFragment
import site.marqstree.kotlinmall.ui.fragment.msg.MsgFragment

class MainActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //申请权限
        begPermissions(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.CAMERA
            //不能申请，不会弹申请对话框
            // 调用系统安装服务时，系统自动弹申请框
            //Manifest.permission.REQUEST_INSTALL_PACKAGES
        )

        initFragments()
        initBottomNav()

    }

    private fun initFragments() {
        addFragment(R.id.mContainer, HomeFragment())
        addFragment(R.id.mContainer, CategoryFragment())
        val cartFrag: Fragment = ARouter.getInstance()
            .build(ProviderRouter.Good.PATH_CART_LIST)
            .navigation() as Fragment
        addFragment(R.id.mContainer, cartFrag)
        addFragment(R.id.mContainer, MsgFragment())
        addFragment(R.id.mContainer, MeFragment())
        changeFragment(0)
    }

    /*
        初始化底部导航切换事件
     */
    private fun initBottomNav() {
        mBottomNavBar.setTabSelectedListener(object : BottomNavigationBar.OnTabSelectedListener {
            override fun onTabReselected(position: Int) {
            }

            override fun onTabUnselected(position: Int) {
            }

            override fun onTabSelected(position: Int) {
                changeFragment(position)
            }
        })
        RxBus.observe<EventAddCart>()
            .subscribe{
                mBottomNavBar.mCartBadge.setText(it.mCount.toString())
            }
        RxBus.observe<EventCartSumCountChange>()
            .subscribe{
                mBottomNavBar.mCartBadge.setText(it.count.toString())
            }
    }

}
